package com.sky.service.impl;

import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.exception.AddressBookBusinessException;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;

    /**
     * 新增地址
     *
     * @param addressBook
     */
    @Override
    public void save(AddressBook addressBook) {
        Long userId = BaseContext.getCurrentId();
        addressBook.setUserId(userId);
        Integer count = addressBookMapper.count();
        if (count == 0) {
            addressBook.setIsDefault(1);
        } else {
            addressBook.setIsDefault(0);
        }
        addressBookMapper.insert(addressBook);
    }

    /**
     * 查询所有地址
     *
     * @return
     */
    @Override
    public List<AddressBook> list() {
        return addressBookMapper.list(BaseContext.getCurrentId());
    }

    /**
     * 设置默认地址
     *
     * @param id
     * @return
     */
    @Override
    public void setDefault(Long id) {
        Long userId = BaseContext.getCurrentId();
        addressBookMapper.cancelOthersDefault(userId);
        addressBookMapper.setDefault(id);
    }

    /**
     * 查询默认地址
     * @return
     */
    @Override
    public AddressBook getDefault() {
        return addressBookMapper.getDefault(BaseContext.getCurrentId());
    }

    /**
     * 修改地址
     * @param addressBook
     */
    @Override
    public void updateAddressBook(AddressBook addressBook) {
        addressBookMapper.updateById(addressBook);
    }

    /**
     * 删除地址
     * @param id
     */
    @Override
    public void delete(Long id) {
        AddressBook addressBook = addressBookMapper.selectById(id);
        if (addressBook.getIsDefault().equals(StatusConstant.ENABLE)){
            throw new AddressBookBusinessException("默认地址不能删除");
        }
        addressBookMapper.deleteById(id);
    }

    /**
     * 根据id查询地址
     * @param id
     * @return
     */
    @Override
    public AddressBook getById(Long id) {
        return addressBookMapper.selectById(id);
    }
}
